var $ = window.$;
var jade = require('jade');
var animate = require('../../util/animate');
var event = require('../../core/event');
var util = require('../../util/index');
var uiUtil = require('../../util/ui');
var config = require('../../core/config');

var _inited = false;

/**
 * 引导
 */

var ret = {
	init: function(){
		if(_inited){
			return;
		}
		this.guide_def = require('../../data/intro/en.json');
		if(!config.isDefaultLang()){
			this.guide_local = require('../../data/intro/'+config.getVal(config.ITEM.LANG)+'.json');
		}
		this.total = this.guide_def.length;
		event.bind(event.events.dialog.guide, 'guide', this);
		event.bind(event.events.key.up, 'guide', this);
		event.lock('key', 'guide');
		_inited = true;
	},

	onEvent: function(e, param){
		if(e == event.events.dialog.guide){
			this.show();
			return true;
		}else if(e == event.events.key.up){
			if(param.key == 27) {
				this.hide();
				return event.result.stopAll;
			}
		}
	},

	changePage: function(delta){
		this.curr += delta;
		if(this.curr < 0){
			this.curr = 0;
			return;
		}else if(this.curr >= this.total){
			this.hide();
			return;
		}
		var item;
		if(this.guide_local){
			item = this.guide_local[this.curr];
		}
		if(!item){
			item = this.guide_def[this.curr];
		}
		this.parent.find('.title').html(item.title);
		this.parent.find('.body').html(item.content);
		if(this.curr == 0){
			this.parent.find('.g_bt span').eq(0).hide();
		}else if(this.curr == this.total - 1){
			this.parent.find('.g_bt span').eq(1).html("Close");
		}else if(this.curr == 1){ //前提是page不能跳变
			this.parent.find('.g_bt span').eq(0).show();
		}else if(this.curr == this.total - 2){
			this.parent.find('.g_bt span').eq(1).html("Next");
		}
	},

	show: function(){
		this.curr = 0;
		//参数准备, param外部已检验
		var tmpl = jade.compileFile('./tmpl/guide/intro.jade');
		var html = tmpl({config: config});
		$('#dialog_layer').append(html);

		var self = this;
		this.parent = $('#dialog_intro');

		this.parent.on('click','.g_click', function(){
			var type = $(this).data('type');
			if(type == 'prev'){
				self.changePage(-1);
			}else if(type == 'next'){
				self.changePage(1);
			}
		});

		this.parent.show();
		uiUtil.dialogInc();
		animate.normalScaleIn(this.parent).then(function(){
			self.changePage(0);
		});
		event.trigger(event.events.global.blur);

	},

	hide: function(){
		var self = this;
		if(!this.parent){
			return;
		}
		animate.normalScaleOut(this.parent).then(function(){
			self.parent.remove();
			self.parent = null;
			uiUtil.dialogDec();
			event.unbindByKey('guide');
		});
		event.unlock();
		_inited = false;
	}
};

module.exports = ret;